<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" clearable placeholder="请输入用户名称" style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" clearable placeholder="请输入手机号码" style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <div class="mr20" style="float: right">
        <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:role:add']" plain type="primary" @click="openSelectUser">
          <template
            #icon>
            <i-ep-plus/>
          </template>
          添加用户
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['system:role:remove']" :disabled="multiple" plain type="danger"
                   @click="cancelAuthUserAll">
          <template #icon>
            <i-ep-delete/>
          </template>
          批量取消授权
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain type="warning" @click="handleClose">
          <template #icon>
            <i-ep-close/>
          </template>
          关闭
        </el-button>
      </el-col>
    </el-row>
    <el-row class="div-height-left">
      <el-col :span="4" class="div-height-left">
        <!--科室树-->
        <dept-tree ref="deptTree" :org-id="queryParams.orgId" @treeClick="treeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-table v-adaptive :border="true" :data="userList" :header-cell-style="$headerCellStyle" highlight-current-row
                  stripe @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column :show-overflow-tooltip="true" label="所属机构" prop="orgName"/>
          <el-table-column :show-overflow-tooltip="true" label="用户名称" prop="userName"/>
          <el-table-column :show-overflow-tooltip="true" label="用户昵称" prop="nickName"/>
          <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email"/>
          <el-table-column :show-overflow-tooltip="true" label="手机" prop="phonenumber"/>
          <el-table-column :align="'center'" label="状态" prop="status">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['sys_normal_disable']" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="创建时间" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
            <template #default="scope">
              <el-button v-hasPerm="['system:role:remove']" type="primary"
                         @click="cancelAuthUser(scope.row)">
                <template #icon>
                  <i-ep-close/>
                </template>
                取消授权
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>
    <select-user ref="select" @ok="handleQuery"/>
  </div>
</template>

<script lang="ts" setup>
import {
  allocatedDeptGroupUserList,
  allocatedUserList,
  authUserCancel,
  authUserCancelAll,
  deptGroupAuthUserCancel,
  deptGroupCancelAll
} from "@/api/system/role";
import selectUser from "@/views/system/role/selectUser.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {useRoute, useRouter} from 'vue-router';
import {useTagsViewStore} from '@/store/modules/tagsView'

const useTagsView = useTagsViewStore()
const route = useRoute()
const router = useRouter()
const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook()
const dictDataMap = ref(dictStore.isTypeGetData('sys_normal_disable'))
const select = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 选中用户组
const userIds = ref([])
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 用户表格数据
const userList = ref([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  userName: undefined,
  phonenumber: undefined,
  // 角色或者科室分组跳转
  businessType: ''
})

// 角色或者科室分组跳转  1:角色管理 ；2：科室分组
const businessType = route.params && route.params.businessType;
let roleId: any = ""
let deptGroupId: any = ""
if (businessType === '1') {
  roleId = route.params && route.params.id;
} else {
  deptGroupId = route.params && route.params.id;
}
const orgId = route.params && route.params.orgId;
queryParams.value.orgId = orgId
queryParams.value.businessType = businessType
if (roleId) {
  queryParams.value.roleId = roleId;
} else if (deptGroupId) {
  queryParams.value.deptGroupId = deptGroupId
}
getList();

/** 查询授权用户列表 */
function getList() {
  if (queryParams.value.businessType === "1") {
    allocatedUserList(queryParams.value).then((response: any) => {
        userList.value = response.rows;
        total.value = response.total;
      }
    );
  } else if (queryParams.value.businessType === "2") {
    allocatedDeptGroupUserList(queryParams.value).then((response: any) => {
        userList.value = response.rows;
        total.value = response.total;
      }
    );
  }
}

// 返回按钮
function handleClose() {
  let obj = {}
  if (queryParams.value.businessType === '1') {
    obj = {path: "/purview/role"}
  } else if (queryParams.value.businessType === '2') {
    obj = {path: "/purview/deptGroup"};
  }
  useTagsView.delView(router.currentRoute).then((_res: any) => {
    router.push(obj)
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = ''
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  userIds.value = selection.map(item => item.userId)
  multiple.value = !selection.length
}

/** 打开授权用户表弹窗 */
function openSelectUser() {
  select.value.show(queryParams.value);
}

/** 取消授权按钮操作 */
function cancelAuthUser(row) {
  if (queryParams.value.businessType === '1') {
    const roleId = queryParams.value.roleId;
    ElMessageBox.confirm('确认要取消该用户"' + row.nickName + '"角色吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      authUserCancel({userId: row.userId, roleId: roleId}).then(() => {
        getList();
        ElMessage.success("取消授权成功");
      })
    }).catch(() => {
    });
  } else if (queryParams.value.businessType === '2') {
    const deptGroupId = queryParams.value.deptGroupId;
    ElMessageBox.confirm('确认要取消该用户"' + row.nickName + '"吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(function () {
      deptGroupAuthUserCancel({userId: row.userId, deptGroupId: deptGroupId}).then(() => {
        getList();
        ElMessage.success("取消授权成功");
      })
    }).catch(() => {
    });
  }
}

/** 批量取消授权按钮操作 */
function cancelAuthUserAll(_row) {
  if (queryParams.value.businessType === '1') {
    const roleId = queryParams.value.roleId;
    const userIdsThis = userIds.value.join(",");
    ElMessageBox.confirm('是否取消选中用户授权数据项？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(function () {
      authUserCancelAll({roleId: roleId, userIds: userIdsThis}).then(() => {
        getList();
        ElMessage.success("取消授权成功");
      })
    }).catch(() => {
    });
  } else if (queryParams.value.businessType === '2') {
    const deptGroupId = queryParams.value.deptGroupId;
    const userIdsThis = userIds.value.join(",");
    ElMessageBox.confirm('是否取消选中用户授权数据项？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(function () {
      deptGroupCancelAll({deptGroupId: deptGroupId, userIds: userIdsThis}).then(() => {
        getList();
        ElMessage.success("取消授权成功");
      })
    }).catch(() => {
    });
  }
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.deptId = obj.id
  getList()
}
</script>
<script lang="ts">
export default {
  name: "AuthUser"
}
</script>
